using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using PerformanceDude.MSBuildShellExtension.Loggers.ErrorListLogger.Properties;

/*
 * Copyright (c) 2007-2011, PerformanceDude.com (infoatperformancedude.com), Lex Li (supportatlextm.com), Rami Abughazaleh (rami.abughazalehatgmail.com)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of PerformanceDude.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
namespace PerformanceDude.MSBuildShellExtension.Loggers.ErrorListLogger
{
    public partial class ErrorListForm : Form
    {
        private readonly ImageList imageList;
        private bool formShown;
        private readonly PersistWindowState windowState;

        public ErrorListForm(MSBuildErrorListLogger m)
        {
            InitializeComponent();
            m.Error += OnError;
            m.Warning += OnWarning;
            //m.Message += OnMessage;
            m.BuildFinished += OnBuildFinished;

            //Resources
            imageList = new ImageList {ColorDepth = ColorDepth.Depth32Bit};
            imageList.Images.Add("Error", Resources.Symbols_Error_16x16);
            imageList.Images.Add("Warning", Resources.Symbols_Warning_16x16);
            imageList.Images.Add("Message", Resources.Symbols_Info_16x16);
            itemListView.SmallImageList = imageList;

            windowState = new PersistWindowState
                              {
                                  Parent = this,
                                  RegistryPath = @"Software\PerformanceDude\MSBuildShellExtension"
                              };
            m.pool.Release();
        }

        private void OnBuildFinished(bool succeeded)
        {
            if (succeeded & itemListView.Items.Count == 0)
            {
                CloseForm();
            }
        }
        
        private void CloseForm()
        {
            formShown = false;
            Close();
        }

        private void OnError(string buildFile, string message, string file, string line, string column)
        {
            noOfErrors++;
            var d = new Data(DataClassification.Error, buildFile, message, file, line, column);
            lock (items)
            {
                items.Add(d);
            }
            if (formShown && errorButton.Checked)
            {
                AddItem(d, true);
            }
            UpdateTitle();
        }

        private void OnWarning(string buildFile, string message, string file, string line, string column)
        {
            noOfWarnings++;
            var d = new Data(DataClassification.Warning, buildFile, message, file, line, column);
            lock (items)
            {
                items.Add(d);
            }
            if (formShown && warningButton.Checked)
            {
                AddItem(d, true);
            }
            UpdateTitle();
        }

        public void OnMessage(string message)
        {
            //noOfMessages++;
            //Data d = new Data(DataClassification.Message, message, "", "", "");
            //lock (items)
            //{
            //    items.Add(d);
            //}
            //if (formShown && messageButton.Checked)
            //{
            //    AddItem(d, true);
            //}
            //UpdateTitle();
        }

        private void UpdateTitle()
        {
            if (InvokeRequired)
            {
                Invoke((MethodInvoker)(UpdateTitle));
                return;
            }

            Text = string.Format("Error List - E:{0} W:{1}", noOfErrors, noOfWarnings);
        }

        private readonly IList<Data> items = new List<Data>();
        private int noOfErrors = 0;
        private int noOfWarnings = 0;
        //private int noOfMessages = 0;

        private void ErrorListForm_Shown(object sender, EventArgs e)
        {
            lock (items)
            {
                foreach (Data item in items)
                {
                    AddItem(item, false);
                }
                RefreshListView();
            }
            formShown = true;
        }

        private delegate void RefreshListViewDelegate();
        private void RefreshListView()
        {
            if (itemListView.InvokeRequired)
            {
                itemListView.Invoke(new RefreshListViewDelegate(itemListView.Refresh));
            }
            else
            {
                itemListView.Refresh();
            }
        }

        private void AddItem(Data data, bool refresh)
        {
            var listViewItem = new ListViewItem(new string[] { "", data.description, data.file, data.line, data.column, data.buildFile }, data.image);
            itemListView.Items.Add(listViewItem);
            if (refresh)
            {
                Refresh();
            }
        }

        private void ErrorListForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            formShown = false;
        }

        private void errorButton_Click(object sender, EventArgs e)
        {
            UpdateItems();
        }

        private void UpdateItems()
        {
            lock (items)
            {
                itemListView.Items.Clear();
                foreach (var data in items)
                {
                    switch (data.classification)
                    {
                        case DataClassification.Error:
                            if (errorButton.Checked) itemListView.Items.Add(new ListViewItem(new string[] { "", data.description, data.file, data.line, data.column, data.buildFile }, data.image));
                            break;
                        case DataClassification.Message:
                            if (messageButton.Checked) itemListView.Items.Add(new ListViewItem(new string[] { "", data.description, data.file, data.line, data.column, data.buildFile }, data.image));
                            break;
                        case DataClassification.Warning:
                            if (warningButton.Checked) itemListView.Items.Add(new ListViewItem(new string[] { "", data.description, data.file, data.line, data.column, data.buildFile }, data.image));
                            break;
                    }
                }
                RefreshListView();
            }
        }

        public bool ShowErrors
        {
            get { return errorButton.Checked; }
            set { errorButton.Checked = value; }
        }

        public bool ShowWarnings
        {
            get { return warningButton.Checked; }
            set { warningButton.Checked = value; }
        }

        private void warningButton_Click(object sender, EventArgs e)
        {
            UpdateItems();
        }

        private void messageButton_Click(object sender, EventArgs e)
        {
            UpdateItems();
        }

        private void itemListView_DoubleClick(object sender, EventArgs e)
        {
            var selectedItems = itemListView.SelectedItems;
            if (selectedItems.Count > 1)
            {
                throw new ApplicationException("Only one selection allowed. Please report this programming error at http://www.codeplex.com/msbuildshellex/WorkItem/List.aspx.");
            }

            if (selectedItems.Count == 1/* && editor != null*/)
            {
                var filename = selectedItems[0].SubItems[2].Text;
                var buildFile = selectedItems[0].SubItems[5].Text;

                // Return if double clicked on item with no filename speified (could be messages)
                // Also return if build project has not been set.
                if (string.IsNullOrEmpty(filename))
                {
                    MessageBox.Show(Resources.filename_could_not_be_resolved);
                    return;
                }

                if (string.IsNullOrEmpty(buildFile))
                {
                    MessageBox.Show(Resources.build_project_could_not_be_resolved);
                    return;
                }

                // Remove directories from filename (example: Properties\AssemblyInfo.cs -> AssemblyInfo.cs)
                var root = buildFile.Substring(0, buildFile.LastIndexOf("\\"));
                var index = filename.LastIndexOf("\\");
                if (index != -1)
                {
                    filename = filename.Substring(index + 1);
                }

                // Get full name of file (example: AssemblyInfo.cs -> c:\projects\test\properties\AssemblyInfo.cs)
                var rootDirectory = new DirectoryInfo(root);
                var files = rootDirectory.GetFiles(filename, SearchOption.AllDirectories);
                if (files.Length == 0)
                {
                    MessageBox.Show(Resources.could_not_find_absolute_path);
                    return;
                }

                var processStartInfo = new ProcessStartInfo(files[0].FullName);
                Process.Start(processStartInfo);
            }
            else
            {
                MessageBox.Show(Resources.selecting_muletiple_files_not_supported);
            }
        }
    }

    public enum DataClassification
    {
        Message,
        Warning,
        Error
    }

    public class Data
    {
        public Data(DataClassification classification, string buildFile, string description, string file, string line, string column)
        {
            this.classification = classification;
            this.buildFile = buildFile;
            this.description = description;
            this.file = file;
            this.line = line;
            this.column = column;
        }

        public string image
        {
            get
            {
                switch (classification)
                {
                    case DataClassification.Error:
                        return "Error";
                    case DataClassification.Warning:
                        return "Warning";
                    case DataClassification.Message:
                        return "Message";
                    default:
                        throw new ApplicationException("Unknown classification: " + classification);
                }
            }
        }

        public DataClassification classification;
        public string description;
        public string buildFile;
        public string file;
        public string line;
        public string column;
    }

}